package org.springblade.application.util;


import com.jcraft.jsch.*;
import com.jcraft.jsch.Channel;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * SFTP传输文件工具类
 * @author dengzhongtao
 */
public class FtpUtils {
/*
	public static void main(String[] args) throws Exception {
		File pdfFile = new File("C:\\Users\\test.zip");
		FileInputStream in = new FileInputStream(pdfFile);
		MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),
				APPLICATION_OCTET_STREAM, in);
		sshSftp(multipartFile.getBytes(),"test.zip");

	}
*/


	private static final String APPLICATION_OCTET_STREAM = "application/octet-stream";
	/**
	 * 利用JSch包实现SFTP上传文件
	 *
	 * @param bytes    文件字节流
	 * @param fileName 文件名
	 * @throws Exception
	 */
	public static void sshSftp(byte[] bytes, String fileName) throws Exception {
		//指定的服务器地址
		String ip = "192.168.1.172";
		//用户名
		String user = "root";
		//密码
		String password = "3h1admin";
		//服务器端口 默认22
		int port = 22;
		//上传文件到指定服务器的指定目录
		String path = "/home";
		Session session = null;
		Channel channel = null;
		JSch jsch = new JSch();
		//采用指定的端口连接服务器
		session = jsch.getSession(user, ip, port);
		//如果服务器连接不上，则抛出异常
		if (session == null) {
			throw new Exception("session is null");
		}
		//设置登陆主机的密码
		session.setPassword(password);
		//设置第一次登陆的时候提示，可选值：(ask | yes | no)
		session.setConfig("StrictHostKeyChecking", "no");
		//设置登陆超时时间
		session.connect(30000);
		OutputStream outstream = null;
		try {
			//创建sftp通信通道
			channel = session.openChannel("sftp");
			channel.connect(1000);
			ChannelSftp sftp = (ChannelSftp) channel;
			//进入服务器指定的文件夹
			sftp.cd(path);
			//以下代码实现从本地上传一个文件到服务器 outStream
			outstream = sftp.put(fileName);
			outstream.write(bytes);
			//下载 inputStream
			//InputStream inputStream = sftp.get(fileName);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//关流操作
			if (outstream != null) {
				outstream.flush();
				outstream.close();
			}
			if (channel != null) {
				channel.disconnect();
			}
			session.disconnect();
		}
	}
}
